package org.jash.sportnews2109.adapter

import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.alibaba.android.arouter.launcher.ARouter
import org.jash.sportnews2109.entity.Category

class CategoryAdapter(fragment: Fragment, val data:MutableList<Category> = mutableListOf()):FragmentStateAdapter(fragment) {
    override fun getItemCount(): Int = data.size

    /**
     * 使用 ARouter 创建 Fragment, 并传入 分类 id
     */
    override fun createFragment(position: Int): Fragment = ARouter.getInstance()
        .build("/news/category")
        .withInt("id", data[position].id)
        .navigation() as Fragment

    /**
     * 利用运算符重载添加数据,并提醒刷新
     */
    operator fun plusAssign(list:List<Category>) {
        val size = data.size
        data += list
        notifyItemRangeInserted(size, list.size)
    }

    /**
     * 用于和 TabLayout 联动
     */
    fun getTitle(position: Int) = data[position].name
}